package engine.logic.login
{
	import engine.data.ModelLocator;
	import engine.logic.loading.LoadingLogic;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.events.TextEvent;
	import flash.text.TextField;
	import flash.ui.Keyboard;
	
	import newx.com.config.StaticIni;
	import newx.com.loader.SwfLoader;

	public class RoleCreateUI implements ILoginUI
	{
		public function RoleCreateUI(clip:MovieClip,container:MovieClip)
		{
			_roleCreateUI=clip;
			_container=container;
		}
		
		private var _completeCallBack:Function;
		
		/**角色创建界面*/
		private var _roleCreateUI:MovieClip;
		private var _container:MovieClip;
		
		private var _raceOccupation:Array;
		private var _occupationId:int=-1;
		private var _raceId:int=-1;
		
		private var _occupationNums:uint=7;
		private var _powDisplayNums:uint=5;
		/**
		 *进度条总长度 
		 */		
		private var _totalProgressNum:Number=-1;
		
		
		static public const Action_Last:String="last";
		static public const Action_Next:String="next";
		/////========================
		private var _backBtn:MovieClip;
		private var _enterBtn:MovieClip;
		private var _nameInput:TextField;
		//=========================================================
		private var _currentRoleURL:Array;
		private var _needCloseURL:String	=	"";
		
		public function show(info:Object=null):void
		{
			//=========初始化
			_backBtn=_roleCreateUI.backBtn;
			_backBtn.gotoAndStop(2);
			_backBtn.buttonMode=true;
			_enterBtn=_roleCreateUI.enterBtn;
			_enterBtn.gotoAndStop(2);
			_enterBtn.buttonMode=true;
			_nameInput=_roleCreateUI.nameInput;
			
			
			if(_totalProgressNum<0)
				_totalProgressNum=MovieClip(getProgressBar(0).bar).width;
			
			_occupationNums=int(StaticIni.getIniVar("GameRaceConfig","occuNums"));
			//===============
			_container.addChild(_roleCreateUI);	
			var raceNums:int=int(StaticIni.getIniVar("GameRaceConfig","raceNums"));
			
			//种族可选职业列表
			_raceOccupation=[];
			for(var j:uint=0;	j<raceNums;	j++)
			{
				_raceOccupation.push(StaticIni.getIniVar("GameRaceConfig","race"+j+"_zyinfo"));
			}
			
			for(var i:uint=0;	i<7;	i++)
			{
				this.getOccupationIcon(i).addEventListener(MouseEvent.MOUSE_DOWN,occupationIconMouseDownHandler);
			}
			
			_enterBtn.addEventListener(MouseEvent.CLICK,enterGameClickHandler);
			_enterBtn.addEventListener(MouseEvent.MOUSE_OVER,btnOverHandler);
			_enterBtn.addEventListener(MouseEvent.MOUSE_OUT,btnOutHandler);
			_backBtn.addEventListener(MouseEvent.CLICK,backBtnClickHandler);
			_backBtn.addEventListener(MouseEvent.MOUSE_OVER,btnOverHandler);
			_backBtn.addEventListener(MouseEvent.MOUSE_OUT,btnOutHandler);
			
			_nameInput.addEventListener(TextEvent.TEXT_INPUT,roleNameInputHandler);
			_nameInput.addEventListener(KeyboardEvent.KEY_DOWN,keyEnterHandler);
			
			
			_raceId=info.raceId;
			LoadingLogic.getInstance().setProcess(0,"");
			SwfLoader.Close(_needCloseURL);
			SwfLoader.StartLoad(this.getBgUrl(_raceId),null,raceBgCompleteHandler,[onBgLoadHandle]);
				
			this.resetOccuIconStateById(_raceId);
			this.selectOccupation(0);
		}
		
		public function hide():void
		{
			///======
			if(_roleCreateUI.parent)
				_roleCreateUI.parent.removeChild(_roleCreateUI);
			
			for(var i:uint=0;	i<7;	i++)
			{
				MovieClip(_roleCreateUI["zy_"+i]).removeEventListener(MouseEvent.MOUSE_DOWN,occupationIconMouseDownHandler);
			}
			
			_nameInput.removeEventListener(TextEvent.TEXT_INPUT,roleNameInputHandler);
			_nameInput.removeEventListener(KeyboardEvent.KEY_DOWN,keyEnterHandler);
			
			
			_enterBtn.removeEventListener(MouseEvent.CLICK,enterGameClickHandler);
			_enterBtn.removeEventListener(MouseEvent.MOUSE_OVER,btnOverHandler);
			_enterBtn.removeEventListener(MouseEvent.MOUSE_OUT,btnOutHandler);
			_backBtn.removeEventListener(MouseEvent.CLICK,backBtnClickHandler);
			_backBtn.removeEventListener(MouseEvent.MOUSE_OVER,btnOverHandler);
			_backBtn.removeEventListener(MouseEvent.MOUSE_OUT,btnOutHandler);	
		}
		
		public function recycle():void
		{
		}
		
		public function set completeCallBack(cb:Function):void
		{
			this._completeCallBack=cb;
		}
		
		private function keyEnterHandler(e:KeyboardEvent):void
		{
			if(	e.keyCode	==	Keyboard.ENTER	)
			{
				enterGameClickHandler();
			}
		}
		
		private function btnOverHandler(e:MouseEvent):void
		{
			MovieClip(e.currentTarget).gotoAndStop(1);
		}
		private function btnOutHandler(e:MouseEvent):void
		{
			MovieClip(e.currentTarget).gotoAndStop(2);
		}
		
		private function backBtnClickHandler(e:MouseEvent):void
		{
			
			var obj:Object=new Object();
			obj.target=this;
			obj.action=RoleCreateUI.Action_Last;
			
			if(null		!=	_completeCallBack)
			{
				_completeCallBack(obj);
			}
		}
		
		private function enterGameClickHandler(e:MouseEvent=null):void
		{
			var obj:Object=new Object();
			obj.target=this;
			obj.action=RoleCreateUI.Action_Next;
			obj.raceId=_raceId;
			obj.occuId=_occupationId;
			obj.roleName=_nameInput.text;
			
			if(null		!=	_completeCallBack)
			{
				_completeCallBack(obj);
			}
		}
		
		private function raceBgCompleteHandler(val:MovieClip,pList:Array):void
		{
			LoadingLogic.getInstance().setProcess(100,"");
			
			while(this.getBgContainer().numChildren>0)
			{
				this.getBgContainer().removeChildAt(0);
			}
			if(	null	!=	val)
				this.getBgContainer().addChild(val);
		}
		
		private function occupationIconMouseDownHandler(e:MouseEvent):void
		{
			if(false 	==	MovieClip(e.currentTarget).buttonMode)	return;

			MovieClip(e.currentTarget).gotoAndStop(1);
			
			var iconName:String=MovieClip(e.currentTarget).name;
			
			var occupationId:int	=int(	iconName.replace("zy_",""));
			
			this.selectOccupation(occupationId);
		}
		
		/**输入角色名检察，超过最大个数时提示错误问题*/
		private function roleNameInputHandler(e:TextEvent):void
		{
			var insertPos:int	=	TextField(e.target).caretIndex;
			var nowStr:String	=	TextField(e.target).text;
			
			var roleName:String	=	nowStr.substring(0,insertPos)+e.text+nowStr.substring(insertPos);
			
			var firstW:String	=	roleName.charAt(0);	
			
			var tipMsg:Object	
			//首字母非法提示
			if(isIllegalLetter(firstW))
			{
				e.preventDefault();	
				
				tipMsg	=	this.getRoleNameTipMsg();
				LoginAlert.showAlert(tipMsg.fError);
				TextField(e.target).stage.focus	=	null;
				return;
			}
			
			//长度限制
			var len:int=roleName.length;
			var maxStrNum:int=this.getRoleMaxNum();
			
			if(len>maxStrNum)
			{
				e.preventDefault();	
				
				tipMsg=this.getRoleNameTipMsg();
				LoginAlert.showAlert(tipMsg.maxError);
				TextField(e.target).stage.focus	=	null;
			}
		}
		//==============
		private function selectOccupation(occuId:int):void
		{
			resetOccupationIconState();
			var occuIcon:MovieClip=this.getOccupationIcon(occuId);
			occuIcon.gotoAndStop(1);
			occuIcon.buttonMode=false;
			
			var occuDisTxt:TextField=this.getOccuDiscribeTxt();
			occuDisTxt.htmlText=this.getOccuDiscribe(occuId);
			
			
			setOccuPowProgress(occuId);
			
			
			LoadingLogic.getInstance().setProcess(0,"");
			
			while(this.getRoleModelContainer().numChildren>0)
			{
				this.getRoleModelContainer().removeChildAt(0);
			}
			
			_currentRoleURL	=	getRoleModelUrl(occuId);
			SwfLoader.Close(_needCloseURL);
			_needCloseURL	=	_currentRoleURL[0];
			SwfLoader.StartLoad(_currentRoleURL[1],null,roleModelCompleteHandler,[onLoadingHandle]);
			this._occupationId=occuId;
		}
		
		private function roleModelCompleteHandler(val:MovieClip,pList:Array):void
		{
			var container:MovieClip	=	getRoleModelContainer();
			
			while(container.numChildren>0)
			{
				container.removeChildAt(0);
			}
			
			if(null		!=	val)
				container.addChild(val);
			
			LoadingLogic.getInstance().setProcess(100,"");
			//静默加载动画
			if(_currentRoleURL)
			{
				SwfLoader.Close(_needCloseURL);
				SwfLoader.StartLoad(_currentRoleURL[0],null,function(mc:MovieClip,pL:Array):void
				{
					//如果静默加载的不是当前需要的，不处理
					if(pL[0]	==	_currentRoleURL[1])
					{
						while(container.numChildren>0)
						{
							container.removeChildAt(0);
						}
						
						if(null		!=	val)
							container.addChild(mc);
					}
				},[_currentRoleURL[1]]);
			}
		}
		
		private function onLoadingHandle(event:Event):void
		{
			if(event.type == ProgressEvent.PROGRESS)
			{
				var e:ProgressEvent	=	event as ProgressEvent;
				LoadingLogic.getInstance().setProcess(e.bytesLoaded*100/e.bytesTotal);
			}
		}
		
		private function onBgLoadHandle(event:Event):void
		{
			if(event.type == ProgressEvent.PROGRESS)
			{
				var e:ProgressEvent	=	event as ProgressEvent;
				LoadingLogic.getInstance().setProcess(e.bytesLoaded*100/e.bytesTotal);
			}
		}
		
		
		private function resetOccuIconStateById(raceId:int):void
		{
			var occuList:Array	=	String(_raceOccupation[raceId]).split(",");
			
			var len:uint=occuList.length;
			var visibleOccuIcon:Array=[];
			var occuIcon:MovieClip;
			var bg:MovieClip=this.getOccuIconBg();
			
			for(var j:uint=0;	j<_occupationNums;		j++)
			{
				occuIcon=this.getOccupationIcon(j);
				occuIcon.gotoAndStop(2);
				occuIcon.visible=false;
				occuIcon.buttonMode=true;
			}
			
			for(var i:uint=0;	i<len;	i++)
			{
				occuIcon=this.getOccupationIcon(occuList[i]);	
				occuIcon.visible=true;
				visibleOccuIcon.push(occuIcon);
			}
			
			this.averageArrange(visibleOccuIcon,bg);
		}
		
		private function resetOccupationIconState():void
		{
			var roleIcon:MovieClip;
			for(var i:uint=0;	i<_occupationNums;	i++)
			{
				roleIcon	=	this.getOccupationIcon(i);
				roleIcon.gotoAndStop(2);
				roleIcon.buttonMode=true;
			}
		}
		
		private function setOccuPowProgress(occuId:int):void
		{	
			var obj:Object=this.getOccuPow(occuId);
			
			var powNameArr:Array=String(obj.pro).split(",");
			
			var progressBar:MovieClip;
			var progressTxt:TextField;
			
			var powArr:Array;
			
			for(var i:uint=0;	i<_powDisplayNums;	i++)
			{
				powArr=String(obj[	powNameArr[i]	]).split(",");
					
				getProgressBar(i).bar.width=_totalProgressNum	*	Number(powArr[1])/Number(powArr[2]);
				getProgressTxt(i).text=StaticIni.getSwfLangStr(powArr[0]);
			}
		}
		
		private function getRoleMaxNum():int
		{
			return 	int(	StaticIni.getIniVar("GameroleNameRestrict","maxNum")	);
		}
		
		private function getRoleNameTipMsg():Object
		{
//			AlertUI.showAlert(StaticIni.getSwfLangStr("UIStr_1000007"),StaticIni.getSwfLangStrVar("UIStr_1000831",[maxStrNum]),AlertUI.OK);
			
			var maxStrNum:int=getRoleMaxNum();
			var obj:Object=new Object();
			obj.title=StaticIni.getSwfLangStr("UIStr_1000007");
			obj.content=StaticIni.getSwfLangStrVar("UIStr_1000831",[maxStrNum]);
			
			obj.maxError	=	StaticIni.getSwfLangStrVar("UIStr_1000967",[maxStrNum]);
			
			obj.fError		=	StaticIni.getSwfLangStr("UIStr_1000831");
			return obj;
		}
		private function getProgressBar(barNum:int):MovieClip
		{
			return _roleCreateUI["progressBar"+barNum];
		}
		
		private function getProgressTxt(barNum:int):TextField
		{
			return TextField(_roleCreateUI["powTxt"+barNum]);
		}
		
		private function getOccuPow(occuId:int):Object
		{
			return StaticIni.getIniObj("ProftypePow_"+occuId);	
		}
		
		private function getRaceFirstOccu(raceId:int):int
		{
			var occuList:Array	=String(	_raceOccupation[raceId]).split(",");
			
			if(occuList.length>0)
					return occuList[0];
			return -1;
		}
		private function getOccuIconBg():MovieClip
		{
			return _roleCreateUI["occupationIconBg"];
		}
		private function getOccupationIcon(occuId:int):MovieClip
		{
			return _roleCreateUI["zy_"+occuId];
		}
		private function getOccuDiscribeTxt():TextField
		{
			return TextField(_roleCreateUI["zy_txt"]);
		}
		private function getOccuDiscribe(occuId:int):String
		{
//			zyinfo0=classdes_0
			var langStr:String=StaticIni.getIniVar("GameLoginConfig","zyinfo"+occuId);	
			
			var discribe:String=StaticIni.getSwfLangStr(langStr);
			
			
			return discribe;
		}
		private function getBgContainer():MovieClip
		{
			return _roleCreateUI["zz_bg"];
		}
		private function getBgUrl(raceId:int):String
		{
			var prefix:String=ModelLocator.getInstance().mainIni.getContent("loginConfig","login_res_path");
			var url:String=StaticIni.getIniVar("GameLoginConfig","zzbg"+raceId);
			return prefix+url;
		}
		private function getRoleModelContainer():MovieClip
		{	
			return _roleCreateUI["zy_bg"];
		}
		
		/**
		 * [真实地址,待机地址] 
		 */		
		private function getRoleModelUrl(occuId:int):Array
		{
			var prefix:String=ModelLocator.getInstance().mainIni.getContent("loginConfig","login_res_path");
			var url:String=StaticIni.getIniVar("GameLoginConfig","zy"+_raceId+"_"+occuId);
			return [prefix+url,prefix+"dj_"+url];
		}
		
		/**
		 * 是否是非法字符
		 * @param str
		 * @return 
		 */		
		private function isIllegalLetter(str:String):Boolean
		{
			var arr:Array=["_","0","1","2","3","4","5","6","7","8","9"];
			for(var i:int=0;i<11;i++)
			{
				if(str==arr[i])
				{
					return true;
				}
			}
			return false;
		}
		
		/**
		 * 将一组显示对象排列在指定的背景上,使用时保证所有显示对象在同一级
		 * @param targetList
		 * @param bg
		 * 
		 */		
		private function averageArrange(targetList:Array,bg:MovieClip):void
		{
			var len:uint=targetList.length;
			
			var gapX:Number;
			var totalWidth:Number=0;
			for(var i:uint=0;	i<len;	i++)
			{
				totalWidth+=	targetList[i].width;
			}
			gapX=(bg.width-totalWidth)/(len-1);
			
			var offsetX:Number=0;
			for(var j:uint=0;	j<len	;j++)
			{
				targetList[j].x=bg.x+offsetX;
				targetList[j].y=bg.y+(bg.height-targetList[j].height)/2;
				
				offsetX+=targetList[j].width+gapX;
			}
		}
		
	}
}